﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Common;
using System.Reflection;
using AnesSystem.Models;
using AnesSystem.Services;
using AnesSystem.ViewModels;
using AnesSystem.Udp;
using AnesSystem.Model;
using System.Threading;
using System.Windows.Threading;

namespace AnesSystem.Controls.CommonTables.CQ.NTZYY
{
    /// <summary>
    /// ShuQIanFangShiCtrs.xaml 的交互逻辑
    /// </summary>
    public partial class ShuQianFangShiCtrl : CustomCommonTableCtrl
    {


        #region Variables
        private DispatcherTimer timer;
        private int i = 0;

        #endregion

        #region Constructor

        public ShuQianFangShiCtrl()
        {
            InitializeComponent();
            InitalTimer();
            qm.CheckChanged += CustomCheckBoxCtrl_CheckChanged_2;
            zgnmz.CheckChanged += CustomCheckBoxCtrl_CheckChanged_3;
            sjzz.CheckChanged += CustomCheckBoxCtrl_CheckChanged_1;
            jg.CheckChanged += jg_CheckChanged; yg.CheckChanged += jg_CheckChanged;
            bg.CheckChanged += jg_CheckChanged; khiv.CheckChanged += jg_CheckChanged;
            md.CheckChanged += jg_CheckChanged;
            IniteRadioBation();
            ksyj.Value = "考虑患者意愿及病情，权衡利弊，同意拟定麻醉方案";
            _xhxtCmp.Value = "无特殊";
            _xhaxtCmp.Value = "无特殊";
            _xyxtCmp.Value = "无特殊"; _hxxtCmp.Value = "无特殊";
            _jssjCmp.Value = "无特殊"; _jzszCmp.Value = "无特殊";
            _nfmxtCmp.Value = "无特殊"; tsqk.Value = "/";
            UdpMangager.Instance.ReceivedMsg += Instance_ReceivedMsg;
            this.Loaded += ShuQianFangShiCtrl_Loaded;

        }



        #endregion

        #region Properties

        #endregion

        #region 依赖属性

        #endregion

        #region Event

        #endregion

        #region Private Methods
        private void InitalTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += Timer_Tick;
        }
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (i < 30)
            {
                PatientLisDataModel p = Util.ExtensionMethods.GetLisData();
                if (p != null && p.Zyh.Equals(DataManager.Instance.CurrentPatientLink.Patient.Zyh) && CheckLisData(p))
                {
                    FillLisData(p);
                    MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                    i = 0;
                    timer.Stop();
                    return;
                }
                i++;
            }
            else
            {
                MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                i = 0;
                timer.Stop();
                MessageBoxCommon.ShowDialog("获取数据结束，若未获取到检验数据，请稍等几分钟重试！！！", MessageBoxCommon.OK);
            }
        }

        #endregion

        #region Public/Protected Methods
        public override void GetLisData()
        {
            string Zyh = DataManager.Instance.CurrentPatientLink.Patient.Zyh;
            if (Zyh == null || "".Equals(Zyh))
            {
                MessageBoxCommon.ShowDialog("请输入住院号重试！！！", MessageBoxCommon.OK);
                return;
            }
            try
            {
                Task.Factory.StartNew(delegate
            {
                PatientLisDataModel p = Util.ExtensionMethods.GetLisData();
                if (p != null && CheckLisData(p))
                {
                    Dispatcher.Invoke(delegate
                    {
                        //FillLisData(p);
                        MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
                    });
                    return;
                }

                UdpModel udpModel = new UdpModel();
                udpModel.PatientId = DataManager.Instance.CurrentPatientLink.Id.ToString();
                udpModel.PatId = DataManager.Instance.CurrentPatientLink.Patient.PatId;
                udpModel.Zycs = DataManager.Instance.CurrentPatientLink.Patient.Zycs;
                udpModel.Zyh = Zyh;
                udpModel.UpdateDate = DateTime.Now.ToString();
                udpModel.AccountID = DataManager.Instance.CurrentPatientLink.Patient.Brxm;
                UdpMangager.Instance.SendUdpServerMsg(ServiceSign.GETLISDATA, udpModel);
                timer.Start();//执行查询方法的线程  
            });
                MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                Common.LogHelper.Error(this.GetType(), ex);
            }
        }
        private void IniteRadioBation()
        {
            new RadioButtonHelper().ChangeRadioSatus(szhm, szhs, szqx, szss);
            new RadioButtonHelper().ChangeRadioSatus(fb_n, fb_y);
            new RadioButtonHelper().ChangeRadioSatus(hxkn_n, hxkn_y);
            new RadioButtonHelper().ChangeRadioSatus(zg_n, zg_y);
            new RadioButtonHelper().ChangeRadioSatus(kkd_yc, kkd_zc);
            new RadioButtonHelper().ChangeRadioSatus(jyw, jyy);
            new RadioButtonHelper().ChangeRadioSatus(tjhdsx, tjhdzc);
            new RadioButtonHelper().ChangeRadioSatus(xgn1, xgn2, xgn3, xgn4);
            new RadioButtonHelper().ChangeRadioSatus(asa1, asa2, asa3, asa4, asa5, asa6);
            new RadioButtonHelper().ChangeRadioSatus(nnis1, nnis2, nnis3, nnis4);
            new RadioButtonHelper().ChangeRadioSatus(pgc, pglh, pgys, pgzd);
            new RadioButtonHelper().ChangeRadioSatus(shztpcea, shztpcia, shztpcna, wypca);
            new RadioButtonHelper().ChangeRadioSatus(qdpgwkn, pgcgkn, pgtqkn);
        }
        #endregion

        #region EventHandlers

        private void CustomCheckBoxCtrl_CheckChanged_3(object sender, RoutedEventArgs e)
        {
            CustomCheckBoxCtrl ctrl = sender as CustomCheckBoxCtrl;
            bool isCheck = ctrl.IsChecked;
            bool qmtrue = qm.IsChecked;
            if (!qmtrue)
            {
                if (isCheck)
                {
                    jbsmtz.Value = true;
                    st.Value = true;
                    xlfx.Value = true;
                    mzyd.Value = "麻醉方式选择椎管内麻醉。①麻醉前适当补充血容量；②注意穿刺轻柔，进针平稳，谨遵原则给药，避免血管损伤出血、局麻药中毒或误穿破蛛网膜等并发症；③严密监测患者心率、血压、脉搏氧饱和度；④抽取阿托品、麻黄碱备用；⑤根据患者需要进行适度镇静；⑥发生麻醉不全改为全身麻醉；⑦备急救物品、药品全套。";
                }

            }
        }


        private void CustomCheckBoxCtrl_CheckChanged_2(object sender, RoutedEventArgs e)
        {
            CustomCheckBoxCtrl ctrl = sender as CustomCheckBoxCtrl;
            bool isCheck = ctrl.IsChecked;
            if (isCheck)
            {
                jbsmtz.Value = true;
                petc.Value = true;
                xqfx.Value = true;
                st.Value = true;
                xlfx.Value = true;
                fjc.Value = true;
                xt.Value = true;
                djz.Value = true;
                mzyd.Value = "麻醉方式选择全身麻醉。①麻醉前适当补充血容量；②气管插管方式选择纤支镜引导下清醒气管插管，全麻诱导后（双腔）气管插管；③麻醉诱导前充分给氧；④麻醉诱导时缓慢注射全麻药，必要时预给小剂量升压药防止血压过低，达到足够麻醉深度后再插管；⑤严密监测患者心率、血压、脉搏氧饱和度、呼气末二氧化碳分压，必要时行动脉及深静脉置管，连续监测动脉血压、picco、中心静脉压、血气分析等；⑥抽取阿托品、麻黄碱备用；⑦备急救物品、药品全套；⑧全程评估麻醉深度，避免发生苏醒延迟；⑨手术结束前给予胃复安、地塞米松、托烷司琼等预防术后恶心呕吐；⑩达到拔管指征后拔出气管导管。";
            }
        }

        private void FillLisData(PatientLisDataModel p)
        {
            Dictionary<string, object> jianYanMap = Util.ExtensionMethods.GetJianYanMap(p.JianYan);
            DataManager.Instance.FillCtrlValue(jianYanMap);
            DataManager.Instance.FillAndSaveXMLTableValue(jianYanMap);
        }

        private void Instance_ReceivedMsg(object sender, UdpMsgAnalysisArgs e)
        {
            if (e.UdpMsgAnalysis.TimeOut.Equals("timeOut"))
            {
                MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
            }
            else if (e.UdpMsgAnalysis.MethodId.Equals(Udp.ServiceSign.GETLISDATA))
            {
                JianYanModel o = e.UdpMsgAnalysis.CustomContent.JsonToObject<JianYanModel>();
                if (o.BloodType != null)
                {
                    DataManager.Instance.CurrentPatientLink.Patient.Xx = o.BloodType;
                }
                Dictionary<string, object> jianYanMap = Util.ExtensionMethods.GetJianYanMap(o);
                DataManager.Instance.FillCtrlValue(jianYanMap);
                DataManager.Instance.FillAndSaveXMLTableValue(jianYanMap);

                MainPageCommonViewModel.Instance.WaitCtrlVisibility = Visibility.Collapsed;
            }
        }

        private void ShuQianFangShiCtrl_Loaded(object sender, RoutedEventArgs e)
        {
            FunctionListHeaderCtrlViewModel.Instance.DisplayButton(true, FunctionListButton.保存, FunctionListButton.打印, FunctionListButton.刷新, FunctionListButton.检验数据);
        }


        private void CustomCheckBoxCtrl_CheckChanged_1(object sender, RoutedEventArgs e)
        {
            CustomCheckBoxCtrl ctrl = sender as CustomCheckBoxCtrl;
            bool isCheck = ctrl.IsChecked;
            bool qmtrue = qm.IsChecked;
            if (!qmtrue)
            {
                if (isCheck)
                {
                    jbsmtz.Value = true;
                    st.Value = true;
                    xlfx.Value = true;
                    mzyd.Value = "麻醉方式选择神经阻滞麻醉。①超声准确显示神经根，全程定位进针，保证药物到位；②用药选择0.25%低浓度罗哌卡因，总量在30ml以内为宜；③操作中注意避开血管、胸膜，避免出血、局麻药中毒及气胸等并发症；④严密监测患者心率、血压、脉搏氧饱和度；⑤根据患者需要进行适度镇静；⑥发生麻醉不全改为全身麻醉；⑦备急救物品、药品全套。";

                }
            }
        }


        #endregion

        public bool CheckLisData(PatientLisDataModel p)
        {
            bool flag = false;
            if (!string.IsNullOrEmpty(p.JianYan.Rbc))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.Hb))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.Hct))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.Plt))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.Wbc))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.NiaoChangGui))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.DianJieZhi))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.GanGongNeng))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.ShenGongNeng))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.XueTang))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.CFanYingDanBai))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.NingXueGongNeng))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.Ecg))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.XueQiFenXi))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.FeiGongNeng))
            {
                return true;
            }
            if (!string.IsNullOrEmpty(p.JianYan.XiongPian))
            {
                return true;
            }
            return flag;
        }


        private void rq_GotFocus(object sender, RoutedEventArgs e)
        {
            CusDatePickerWin cusDatePicker = new CusDatePickerWin();
            cusDatePicker.SelectedDateTime = DateTime.Now;
            cusDatePicker.ShowDialog();
            if (cusDatePicker.Result)
            {
                rq.Value = cusDatePicker.SelectedDateTime.ToString(DateFormat.DATE_FORMAT_STR_YMD_CN);//xxxx年xx月xx日
            }
        }

        private void jg_CheckChanged(object sender, RoutedEventArgs e)
        {
            CustomCheckBoxCtrl cutrue = sender as CustomCheckBoxCtrl;
            bool istrue = cutrue.IsChecked;
            if (istrue)
            {
                DataManager.Instance.CurrentPatientLink.InfectedPatient = true;
                UdpMangager.Instance.IsNeedSendMessage = false;
                PatientLinkService.Instance.AddUpdate(DataManager.Instance.CurrentPatientLink);
            }
            else
            {
                DataManager.Instance.CurrentPatientLink.InfectedPatient = false;
                UdpMangager.Instance.IsNeedSendMessage = false;
                PatientLinkService.Instance.AddUpdate(DataManager.Instance.CurrentPatientLink);
            }

        }
    }
}
